<?php
/*
Plugin Name: ET Testimonials
Plugin URI: http://code.google.com/p/et-testimonials/
Description: Manage Testimonials on your WordPress site using custom post types and shortcodes
Version: 0.1.0
Author: Emyr Thomas
License: GPL2
*/

/*  Copyright 2011 Emyr Thomas (email : emyr.thomas@gmail.com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License, version 2, as 
    published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

add_action( 'init', 'create_et_testimonial_post_type' );
function create_et_testimonial_post_type() {
         $labels = array(
                'name'              => __( 'Testimonial Categories' ),
                'singular_name'     => __( 'Testimonial Category' ),
                'search_items'      => __( 'Search Testimonial Categories' ),
                'all_items'         => __( 'All Testimonial Categories' ),
                'parent_item'       => __( 'Parent Testimonial Category' ),    
                'parent_item_colon' => __( 'Parent Testimonial Category:' ),
                'edit_item'         => __( 'Edit Testimonial Category' ),
                'update_item'       => __( 'Update Testimonial Category' ),
                'add_new_item'      => __( 'Add New Testimonial Category' ),
                'new_item_name'     => __( 'New Testimonial Category Name' ),
        );
        register_taxonomy( 'et_testimonial_category', array( 'et_testimonial' ), array(
                'hierarchical' => true,
                'labels'       => $labels,
                'show_ui'      => true,
                'query_var'    => true,
                'rewrite'      => array( 'slug' => 'testimonial-category' ),
        ));

        register_post_type( 'et_testimonial',
                array(
                        'labels' => array(
                                'name'          => __( 'Testimonials' ),
                                'singular_name' => __( 'Testimonial' ),
                                'edit_item'     => __( 'Edit Testimonial' ),
                                'add_new_item'  => __( 'Add Testimonial' )
                        ),                                
                        'public'          => true,       
                        'show_ui'         => true,               
                        'capability_type' => 'post',          
                        'rewrite'         => array( 'slug' => 'testimonial', 'with_front' => false ),
                        'taxonomies'      => array( 'et_testimonial_category' ),
                        'supports'        => array( 'title','editor','thumbnail' )
                )                                                 
        );
}

// Change 'Enter title here' text on post screen
add_action('gettext', 'change_et_testimonial_title_text');
function change_et_testimonial_title_text( $translation ) {
    global $post;
    if( isset( $post ) ) {
        switch( $post->post_type ) {
            case 'et_testimonial' :
                if( $translation == 'Enter title here' )
                    return 'Customer name';
            break;
        }
    }
    return $translation;
}

// Add filter to ensure the text Testimonial, or testimonial, is displayed when user updates a testimonial. 
if( is_admin() ) add_filter('post_updated_messages', 'et_testimonial_updated_messages');
function et_testimonial_updated_messages( $messages ) {
    global $post, $post_ID;

        $messages['et_testimonial'] = array(
        0 => '', // Unused. Messages start at index 1.
        1 => sprintf( 'Testimonial updated. <a href="%s">View testimonial</a>', esc_url( get_permalink( $post->ID ) ) ),
        2 => 'Custom field updated.',
        3 => 'Custom field deleted.',
        4 => 'Testimonial updated.',
        /* translators: %s: date and time of the revision */
        5 => isset( $_GET['revision'] ) ? sprintf( 'Testimonial restored to revision from %s', wp_post_revision_title( (int)$_GET['revision'], false ) ) : false,
        6 => sprintf( 'Testimonial published. <a href="%s">View testimonial</a>', esc_url( get_permalink( $post->ID ) ) ),
        7 => 'Testimonial saved.',
        8 => sprintf( 'Testimonial submitted. <a target="_blank" href="%s">Preview testimonial</a>', esc_url( add_query_arg( 'preview', 'true', get_permalink($post->ID) ) ) ),
        9 => sprintf( 'Testimonial scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview testimonial</a>', date_i18n( 'M j, Y @ G:i', strtotime( $post->post_date ) ), esc_url( get_permalink( $post->ID ) ) ),
        10 => sprintf( 'Testimonial draft updated. <a target="_blank" href="%s">Preview testimonial</a>', esc_url( add_query_arg( 'preview', 'true', get_permalink( $post->ID ) ) ) )
    );

    return $messages;
}

if( is_admin() ) add_action( 'add_meta_boxes', 'add_meta_boxes' );

function add_meta_boxes() {
    if( function_exists( 'add_meta_box' ) ) {
        add_meta_box( 'et-testimonial-company', 'Company Information', 'company_info', 'et_testimonial', 'normal', 'low' );
    }
}

function company_info( $post ) {
    ?><p>
    <?php wp_nonce_field( plugin_basename( __FILE__ ), 'et_testimonial_nonce' ); ?>
    <label for="testimonial_company_name">Company Name</label>
    <input style="width:100%" type="text" name="testimonial_company_name" id="testimonial_company_name" value="<?php echo get_post_meta( $post->ID, 'et_testimonial_company_name', 1 ); ?>" />
    </p>
    <p>
    <label for="testimonial_company_url">Company URL</label>
    <input style="width:100%" type="text" name="testimonial_company_url" id="testimonial_company_url" value="<?php echo get_post_meta( $post->ID, 'et_testimonial_company_url', 1 ); ?>" />
    </p><?php
}

add_action( 'save_post', 'save_postdata' );

function save_postdata( $id ) {
    if( ! isset( $_POST['et_testimonial_nonce'] ) || ! wp_verify_nonce( $_POST['et_testimonial_nonce'], plugin_basename( __FILE__ ) ) )
        return $id;

    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $id;

    if( 'et_testimonial' == $_POST['post_type'] ) {
        if( ! current_user_can( 'edit_page', $id ) )
            return $id;

        if( isset( $_POST['testimonial_company_name'] ) && ! empty( $_POST['testimonial_company_name'] ) )
            update_post_meta( $id, 'et_testimonial_company_name', strip_tags( $_POST['testimonial_company_name'] ) );

        if( isset( $_POST['testimonial_company_url'] ) && ! empty( $_POST['testimonial_company_url'] ) )
            update_post_meta( $id, 'et_testimonial_company_url', strip_tags( $_POST['testimonial_company_url'] ) );
    }
}

// Register the company column
function add_new_testimonial_columns( $columns ) {
	$new_columns['title'] = __( 'Customer Name' );
	$new_columns['et_testimonial_company_name'] = __( 'Company' );
        $new_columns['et_testimonial_category'] = __( 'Categories' );
	$new_columns['date'] = __( 'Date' );
 
	return $new_columns;
}
add_filter( 'manage_edit-et_testimonial_columns', 'add_new_testimonial_columns' );

// Display the column content
function manage_testimonial_columns( $column_name, $post_id ) {
    switch( $column_name ) {
        case 'et_testimonial_company_name':
	    $company = get_post_meta($post_id, 'et_testimonial_company_name', true);
	    $url = get_post_meta($post_id, 'et_testimonial_company_url', true);
	    if ( !$company )
	        $company = '';
            if ( !empty( $url ) )
                $company = '<a href="' . $url . '">' . $company . '</a>';
	    echo $company;
            break;

        case 'et_testimonial_category':
            $terms = wp_get_object_terms($post_id, 'et_testimonial_category');
            $categories = array();
            foreach( $terms as $term ) {
                $categories[] = '<a href="edit.php?post_type=et_testimonial&et_testimonial_category=' . $term->slug .'">' . $term->name . '</a>';
            }
            echo implode( ', ', $categories );
            break;

        default:
            break;
    }
}
add_action( 'manage_et_testimonial_posts_custom_column', 'manage_testimonial_columns', 10, 2 );

// Register the column as sortable
function manage_sortable_columns( $columns ) {
	$columns['et_testimonial_company_name'] = 'et_testimonial_company_name';
 
	return $columns;
}
add_filter( 'manage_edit-et_testimonial_sortable_columns', 'manage_sortable_columns' );

function company_column_orderby( $vars ) {
	if ( isset( $vars['orderby'] ) && 'et_testimonial_company_name' == $vars['orderby'] ) {
		$vars = array_merge( $vars, array(
			'meta_key' => 'et_testimonial_company_name',
			'orderby' => 'meta_value'
		) );
	}
 
	return $vars;
}
add_filter( 'request', 'company_column_orderby' );

add_shortcode('testimonial', 'ea_testimonial_shortcode');
function ea_testimonial_shortcode( $atts ) {
    extract( shortcode_atts( array(
        'cat'         => '',
        'id'          => '',
        'title'       => '',
        'numberposts' => -1,
        'post_status' => 'publish',
        'orderby'     => 'menu_order ID',
        'order'       => 'ASC'
    ), $atts ) );

    if( !empty( $id ) ) {
        $testimonials = get_posts( array(
        'order'          => $order,
        'orderby'        => $orderby,
        'p'              => $id,
        'post_type'      => 'et_testimonial',
        'post_status'    => $post_status,
        'numberposts'    => $numberposts) );
    } else {
        $testimonials = get_posts( array(
        'order'          => $order,
        'orderby'        => $orderby,
        'et_testimonial_category'   => $cat,
        'post_type'      => 'et_testimonial',
        'post_status'    => $post_status,
        'numberposts'    => $numberposts) );
    }

    if( $testimonials && !empty( $title ) ) {
        $shortcode .= '<p class="testimonial-title">'.$title.'</p>';
    }

    if( $testimonials ) {
        foreach( $testimonials as $testimonial ) {
            $customer = $testimonial->post_title;
            $company = get_post_meta($testimonial->ID, 'et_testimonial_company_name', true);
            $url = get_post_meta($testimonial->ID, 'et_testimonial_company_url', true);
            $content = wpautop( $testimonial->post_content );

            $shortcode .= '<div class="testimonial">';
            $shortcode .= $content;
            $shortcode .= '<p class="testimonial-client"><strong>' . $customer . '</strong>';
            if( !empty( $company ) ) {
                if( !empty( $url ) )
                    $shortcode .= ' - <a href="' . $url . '">' . $company . '</a>';
                else 
                    $shortcode .= ' - ' . $company;
            }
            $shortcode .= '</p></div>';
        }
    }

    $testimonial_shortcode = do_shortcode( $shortcode );
    return $shortcode;
}

?>
